package com.example.demo.core.http;

import com.example.demo.core.exception.ProgramException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.web.client.RestTemplate;

/**
 * 自定义请求类
 *
 * @author yujie
 * @date 2021-05-27 22:29
 */
public class CustomRestTemplate {
    private Logger logger = LoggerFactory.getLogger(CustomRestTemplate.class);

    private static final String HTTP_START = "http://";
    private static final String HTTPS_START = "https://";

    private static class SingletonRestTemplate {
        static final RestTemplate INSTANCE = new RestTemplate();
    }


    public static RestTemplate getInstance() {
        return SingletonRestTemplate.INSTANCE;
    }

    /**
     * post 请求
     *
     * @param url  请求路径
     * @param data body数据
     * @return
     */
    public static String httpPostForObject(String url, String data, String accept, String contentEncoding, String contentType) {

        if (!url.startsWith(HTTP_START)) {
            throw new ProgramException("当前只处理http请求");
        }
        HttpHeaders headers = new HttpHeaders();
        headers.add("Accept", accept);
        headers.add("Content-Encoding", contentEncoding);
        headers.add("Content-Type", contentType);
        HttpEntity<String> requestEntity = new HttpEntity<>(data, headers);
        return getInstance().postForObject(url, requestEntity, String.class);
    }


}
